import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:ichinesereader/controller/assessments.dart';
import 'package:ichinesereader/models/book/BookItem.dart';
import 'package:ichinesereader/constants.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:ichinesereader/widgets/tools/pdfviewer.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:just_the_tooltip/just_the_tooltip.dart';
import '../../pages/teacher/evaluationRecordReview.dart';
import '../../themes/appTheme.dart';

// ignore: must_be_immutable
class AssessmentBookGridWithCheckBox extends StatelessWidget {
  AssessmentBookGridWithCheckBox({
    Key? key,
    required this.books,
    required this.readingType,
  }) : super(key: key);

  List<BookItem> books;
  NanhaiBookReadingTypes readingType;
  final box = Hive.box('appconfig');

  @override
  Widget build(BuildContext context) {
    Log.debug('build AssessmentBookGridWithCheckBox');

    final AssessmentsController _bookcontroller = Get.find();

    return GridView.builder(
        padding: EdgeInsets.zero,
        gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
            maxCrossAxisExtent: 240,
            childAspectRatio: 156 / 200,
            crossAxisSpacing: 20,
            mainAxisSpacing: 20),
        itemCount: books.length,
        itemBuilder: (BuildContext ctx, index) {
          //String bid = books[index].bookId ?? '';
          String btitle = books[index].bookTitle ?? '';
          String bcode = books[index].bookCode ?? '';
          String bimage = books[index].bookImageLink ?? '';
          String desc = books[index].description ?? '';
          String viewMode = books[index].viewMode ?? 'LANDSCAPE';
          //bool ifAssigned = books[index].ifAssigned ?? false;
          box.put(CacheManagerKey['_viewMode'].toString(), viewMode);

          return Container(
            decoration: BoxDecoration(
              color: Get.isDarkMode
                  ? AppTheme.colors.darkTheme2
                  : Colors.white.withOpacity(0.3),
              borderRadius: BorderRadius.circular(4.5),
              boxShadow: [
                BoxShadow(
                  blurRadius: 12,
                  spreadRadius: 1,
                  color: Get.isDarkMode
                      ? Colors.transparent
                      : Colors.black.withOpacity(0.1),
                  offset: Offset(1, 1),
                ),
              ],
            ),
            padding: EdgeInsets.fromLTRB(12.0, 12.0, 0.0, 0.0),
            //alignment: Alignment.center,
            //margin: const EdgeInsets.only(top: 15.0),
            child: Padding(
              padding: const EdgeInsets.all(0.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Expanded(
                    //padding: const EdgeInsets.all(8.0),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                      children: <Widget>[
                        Expanded(
                          child: MouseRegion(
                              cursor: SystemMouseCursors.click,
                              child: GestureDetector(
                                onTap: () {
                                  //Log.debug(bimage);
                                  if (bcode == 'RUNNING_RECORD' &&
                                      bimage != '') {
                                    if (GetPlatform.isDesktop ||
                                        GetPlatform.isMacOS ||
                                        GetPlatform.isWeb) {
                                      launchInWebViewWithJavaScript(
                                          '${Constants.BaseURL}icr/student/book/${books[index].bookId}');
                                    } else {
                                      int end = bimage.lastIndexOf('.');
                                      String pdfaddress =
                                          bimage.substring(0, end);
                                      pdfaddress = pdfaddress + '.pdf';
                                      Log.debug(pdfaddress);

                                      if (pdfaddress.contains('runingrecords'))
                                        Get.to(() =>
                                            PDFViewer(pdfaddress: pdfaddress));
                                    }
                                  }

                                  if (bcode.startsWith('IBDP_')) {
                                    String pdfaddress =
                                        'https://resources.ichinesereader.com/media/ib-speaking/${books[index].bookId}.pdf#toolbar=0';
                                    Log.debug(pdfaddress);
                                    Get.to(() =>
                                        PDFViewer(pdfaddress: pdfaddress));
                                  }

                                  if (bcode == 'BENCHMARK_TEST') {
                                    String bookId = books[index].bookId ?? '';
                                    if (bookId.isNotEmpty) {
                                      _bookcontroller
                                          .fetchQuestionGroupByBookCode(bookId);
                                      Get.to(() => EvaluationRecordReviewPage(),
                                          arguments: {
                                            'title':
                                                books[index].bookTitle ?? '',
                                            'status': 'NEW'
                                          });
                                    }
                                  }
                                },
                                child: JustTheTooltip(
                                  backgroundColor: Get.isDarkMode
                                      ? Get.theme.primaryColor
                                      : Get.theme.primaryColorLight,
                                  preferredDirection: AxisDirection.right,
                                  elevation: 4.0,
                                  content: Padding(
                                    padding: EdgeInsets.all(12.0),
                                    child: Container(
                                      width: 150,
                                      child: Text(
                                        desc,
                                        softWrap: true,
                                        maxLines: 10,
                                        style: TextStyle(
                                          letterSpacing: 1.0,
                                          fontSize: 15,
                                          color: Get.isDarkMode
                                              ? Get.theme.primaryColorDark
                                              : Colors.blueGrey,
                                        ),
                                        overflow: TextOverflow.ellipsis,
                                      ),
                                    ),
                                  ),
                                  child: Image.network(
                                    bimage,
                                    height: 200.0,
                                    width: 156,
                                    fit: BoxFit.cover,
                                    errorBuilder: (context, error, stackTrace) {
                                      return Image.asset(
                                          'assets/images/imagenotavailable.png',
                                          height: 200.0,
                                          width: 156,
                                          fit: BoxFit.cover);
                                    },
                                  ),
                                ),
                              )),
                        ),
                        Container(
                          height: 40,
                          margin: const EdgeInsets.only(top: 6.0),
                          child: MouseRegion(
                              cursor: SystemMouseCursors.click,
                              child: GestureDetector(
                                onTap: () {
                                  if (bcode == 'RUNNING_RECORD' &&
                                      bimage != '') {
                                    if (GetPlatform.isDesktop ||
                                        GetPlatform.isMacOS ||
                                        GetPlatform.isWeb) {
                                      launchInWebViewWithJavaScript(
                                          '${Constants.BaseURL}icr/student/book/${books[index].bookId}');
                                    } else {
                                      int end = bimage.lastIndexOf('.');
                                      String pdfaddress =
                                          bimage.substring(0, end);
                                      pdfaddress = pdfaddress + '.pdf';
                                      Log.debug(pdfaddress);

                                      if (pdfaddress.contains('runingrecords'))
                                        Get.to(() =>
                                            PDFViewer(pdfaddress: pdfaddress));
                                    }
                                  }

                                  if (bcode.startsWith('IBDP_')) {
                                    String pdfaddress =
                                        'https://resources.ichinesereader.com/media/ib-speaking/${books[index].bookId}.pdf#toolbar=0';
                                    Log.debug(pdfaddress);
                                    Get.to(() =>
                                        PDFViewer(pdfaddress: pdfaddress));
                                  }

                                  if (bcode == 'BENCHMARK_TEST') {
                                    String bookId = books[index].bookId ?? '';
                                    if (bookId.isNotEmpty) {
                                      _bookcontroller
                                          .fetchQuestionGroupByBookCode(bookId);
                                      Get.to(() => EvaluationRecordReviewPage(),
                                          arguments: {
                                            'title':
                                                books[index].bookTitle ?? '',
                                            'status': 'NEW'
                                          });
                                    }
                                  }
                                },
                                child: Text(
                                  ' $btitle',
                                  maxLines: 2,
                                  overflow: TextOverflow.fade,
                                  style: TextStyle(
                                      color: Get.isDarkMode
                                          ? Get.theme.primaryColorDark
                                          : Colors.black.withOpacity(0.75)),
                                ),
                              )),
                        ),
                      ],
                    ),
                  ),
                  Container(
                    margin: const EdgeInsets.only(left: 8.0, right: 8),
                    child: Column(
                      children: [
                        // Padding(
                        //   padding: const EdgeInsets.only(top: 15.0),
                        // ),
                        SizedBox(
                          height: 24,
                          width: 24,
                          child: Checkbox(
                              value: books[index].selected ?? false,
                              onChanged: (value) {
                                // // var item = books
                                // //     .where((element) => element.bookId == books[index].bookId).first;
                                if (value == true) {
                                  _bookcontroller
                                      .addToSelectedBenchmarkBookItems(
                                          books[index], this.readingType);
                                } else {
                                  _bookcontroller
                                      .removeFromSelectedBenchmarkBookItems(
                                          books[index], this.readingType);
                                }
                                books[index].selected = value;
                                //   setState(() {
                                //  books[index].selected = value;
                                // });
                              }),
                        ),
                        // Padding(
                        //   padding: const EdgeInsets.only(top: 15.0),
                        // ),
                        // Icon(
                        //   Icons.book,
                        //   size: 24.0,
                        //   color: ifAssigned
                        //       ? hexStringToHexInt('#ffc107')
                        //       : Get.isDarkMode
                        //           ? Get.theme.primaryColorDark
                        //           : Get.theme.primaryColorLight,
                        // ),
                        Visibility(
                          visible: bcode == 'RUNNING_RECORD',
                          child: Padding(
                            padding: const EdgeInsets.only(top: 12.0),
                          ),
                        ),
                        Visibility(
                            visible: bcode == 'RUNNING_RECORD',
                            child: MouseRegion(
                              cursor: SystemMouseCursors.click,
                              child: GestureDetector(
                                onTap: () {
                                  int end = bimage.lastIndexOf('.');
                                  String pdfaddress = bimage.substring(0, end);
                                  pdfaddress = pdfaddress + '.pdf';
                                  Log.debug(pdfaddress);

                                  if (pdfaddress.contains('runingrecords'))
                                    Get.to(() =>
                                        PDFViewer(pdfaddress: pdfaddress));
                                },
                                child: Icon(Icons.picture_as_pdf_rounded,
                                    size: 24.0,
                                    color: Get.isDarkMode
                                        ? Get.theme.primaryColorDark
                                        : Get.theme.primaryColorLight),
                              ),
                            ))
                      ],
                    ),
                  )
                ],
              ),
            ),
          );
        });
  }
}
